package com.itheima.aop;

import com.itheima.mapper.LoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class LoginLog {
    @Resource
    private LoginLogMapper loginLogMapper;

    @Around("execution(* com.itheima.service.LoginService.login(..))")
    public Object loginAround(ProceedingJoinPoint joinPoint) throws Throwable {


        long start = System.currentTimeMillis();
        Object[] args = joinPoint.getArgs(); // 获取登录参数
        String password = null;
        String username = null;

        for (Object obj : args) {

            if (obj instanceof Emp) {
                Emp emp = (Emp) obj;
                password = emp.getPassword();
                username = emp.getUsername();
            }

        }

        Object proceed = null;
        LoginInfo result = null;
        Throwable exception = null;

        try {
            proceed = joinPoint.proceed();
            result = (LoginInfo) proceed;
        } catch (Throwable throwable) {
            exception = throwable;
            log.error("登录过程中发生异常", throwable);
        }

        long end = System.currentTimeMillis();

        // 记录登录日志
        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        empLoginLog.setLoginTime(LocalDateTime.now());
        empLoginLog.setCostTime(end - start);

        if (result != null) {
            // 登录成功的情况
            empLoginLog.setJwt(result.getToken());
            empLoginLog.setIsSuccess((short) 1);
        } else {
            // 登录失败的情况
            empLoginLog.setJwt(null);
            empLoginLog.setIsSuccess((short) 0);
        }

        loginLogMapper.insert(empLoginLog);

        // 如果有异常，重新抛出
        if (exception != null) {
            throw exception;
        }

        return proceed;
    }
}
